package com.tengju.data.infrastructure.repository.cdc;

import com.tengju.data.domain.model.cdc.CdcUserRepository;
import com.tengju.data.infrastructure.persistence.mybatis.dataobject.BlackUserInfoDO;
import com.tengju.data.infrastructure.persistence.mybatis.mapper.data.custom.BlackUserInfoDOCustomMapper;
import com.tengju.user.domain.shared.DateUtil;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Date;

@Repository
public class CdcUserRepositoryImpl implements CdcUserRepository {



    @Resource
    private BlackUserInfoDOCustomMapper blackUserInfoDOCustomMapper;



    @Override
    @Transactional(value = "dealerTransactionManager",rollbackFor = Exception.class)
    public void deleteByIdCode(long idCode) {
        blackUserInfoDOCustomMapper.deleteByIdCode(idCode);
    }


    @Override
    @Transactional(value = "dealerTransactionManager",rollbackFor = Exception.class)
    public void saveOrUpdateByCdc(long idCode, long pIdCode, int level, String levelChangeTime, @NotNull String sourceChangeTime) {
        BlackUserInfoDO blackUserInfoDO = blackUserInfoDOCustomMapper.getByIdCode(idCode);
        BlackUserInfoDO newBlackUserInfo = new BlackUserInfoDO();
        Date now = new Date();
        newBlackUserInfo.setIdCode(idCode);
        newBlackUserInfo.setLevel((byte)level);
        newBlackUserInfo.setLevelChangeTime(DateUtil.parseStringToDate(DateUtil.DATE_TIME_FORMAT,levelChangeTime));
        newBlackUserInfo.setSourceChangeTime(DateUtil.parseStringToDate(DateUtil.DATE_TIME_FORMAT,sourceChangeTime));
        newBlackUserInfo.setpIdCode(pIdCode);
        newBlackUserInfo.setUpdateTime(now);
        if (blackUserInfoDO == null || blackUserInfoDO.getSourceChangeTime() == null) {
            newBlackUserInfo.setCreateTime(now);
            blackUserInfoDOCustomMapper.insert(newBlackUserInfo);
            return;
        }
        // 数据库中变更时间比binlog记录时间靠后，这条数据直接丢弃
        if (blackUserInfoDO.getSourceChangeTime().after(DateUtil.parseStringToDate(DateUtil.DATE_TIME_FORMAT,sourceChangeTime))) {
            return;
        }
        newBlackUserInfo.setId(blackUserInfoDO.getId());
        blackUserInfoDOCustomMapper.updateByPrimaryKeySelective(newBlackUserInfo);
    }


}
